﻿using System;
using System.Xml;

namespace PackageStore
{
    public partial class Default : System.Web.UI.Page
    {
        private static int page = 1;
        private static int pageSize = 15;
        private static int startNum
        {
            get
            {
                return (page - 1) * pageSize;
            }
        }
        private static int endNum
        {
            get { return startNum + pageSize; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string k = Request["apiKey"];
            if (k != null && k == "14245e110457a93b2c6b091e7cf842577c9c1fa543364141374535384534")
            {
                if (!int.TryParse(Request["p"], out page))
                    page = 1;

                int.TryParse(Request["ps"], out pageSize);

                string xmlPath = Server.MapPath("~/packageList.xml");
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlPath);
                XmlNodeList list = doc.SelectNodes("/packageList/package");

                XmlWriterSettings s = new XmlWriterSettings();
                s.Indent = true;
                XmlWriter w = XmlWriter.Create(Response.Output, s);
                w.WriteStartDocument();
                w.WriteStartElement("packageList");
                w.WriteAttributeString("total", list.Count.ToString());

                for (int i = startNum; i < list.Count; i++)
                {
                    if (i >= endNum) break;

                    XmlNode n = list[i];
                    w.WriteStartElement("package");
                    w.WriteElementString("id", n["id"].InnerText);
                    w.WriteElementString("version", n["version"].InnerText);
                    w.WriteElementString("description", n["description"].InnerText);
                    w.WriteElementString("authors", n["authors"].InnerText);
                    w.WriteElementString("size", n["size"].InnerText);
                    w.WriteElementString("md5", n["md5"].InnerText);
                    w.WriteElementString("publishTime", n["publishTime"].InnerText);
                    w.WriteEndElement();
                }

                w.WriteEndElement();
                w.WriteEndDocument();
                w.Flush();
                w.Close();
            }
            Response.ContentType = "text/xml";
            Response.Flush();
            Response.End();
        }
    }
}